package com.gengzp.rpc.core.impl;

import com.gengzp.rpc.annotation.RemoteTransactional;
import com.gengzp.rpc.core.RpcConsumerCoreFunc;
import com.gengzp.rpc.core.RpcInvocationCoreFunc;
import com.gengzp.rpc.core.RpcRequestIdentificationCoreFunc;
import com.gengzp.rpc.exception.RpcException;
import com.gengzp.rpc.model.common.req.RpcRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * @ClassName RpcConsumerCoreFuncImpl
 * @Description rpc远程调用消费者端核心方法实现类
 * @Author gengzp
 * @Date 2025/8/23 18:06
 */
@Component
public class RpcConsumerCoreFuncImpl implements RpcConsumerCoreFunc {

    @Autowired
    private RpcInvocationCoreFunc rpcInvocationCoreFunc;

    @Autowired
    private RpcRequestIdentificationCoreFunc rpcRequestIdentificationCoreFunc;

    @Override
    public Object doExecuteRemoteCallConsumer(String remoteServiceName,
                                              Object proxy,
                                              Method method,
                                              Object[] args) throws RpcException {
        // 1.首先校验调用的方法是否启用远程事务, 将事务管理状态添加到线程变量
        rpcRequestIdentificationCoreFunc.saveEnableRemoteTransactionFlag(method.isAnnotationPresent(RemoteTransactional.class));
        // 2.获取请求url
        String remoteCallUrl = rpcInvocationCoreFunc.getRemoteServiceAddress(remoteServiceName);
        // 3.组装请求参数
        RpcRequest rpcRequestParam = rpcInvocationCoreFunc.buildRpcRequest(remoteServiceName, proxy, method, args);
        // 4.获取用户自定义远程调用http请求头
        Map<String, String> remoteCallHeaders = rpcInvocationCoreFunc.getCustomRemoteCallRequestHeader();
        // 5.远程方法的返回值类型
        Type genericReturnType = method.getGenericReturnType();
        // 6.发起http请求, 调用远程方法
        return rpcInvocationCoreFunc.doHttpRequest2RemoteService(
                remoteCallUrl, rpcRequestParam, remoteCallHeaders, genericReturnType);
    }

}
